<template>
  <div class="editor-layout">
    <TopHeader />
    <div class="editor-container">
      <LeftSidebar />
      <EditorCanvas ref="editorCanvas" />
      <RightSidebar />
    </div>
    <PreviewDialog :visible.sync="previewVisible" :schema="previewSchema" />
  </div>
</template>

<script>
import { EventBus } from '@/event-bus.js';
import TopHeader from '@/components/TopHeader.vue';
import LeftSidebar from '@/components/LeftSidebar.vue';
import EditorCanvas from '@/components/EditorCanvas.vue';
import RightSidebar from '@/components/RightSidebar.vue';
import PreviewDialog from '@/components/PreviewDialog.vue';

export default {
  name: 'EditorView',
  components: {
    TopHeader,
    LeftSidebar,
    EditorCanvas,
    RightSidebar,
    PreviewDialog
  },
  data() {
    return {
      previewVisible: false,
      previewSchema: []
    };
  },
  mounted() {
    EventBus.$on('save-canvas', this.saveCanvas);
    EventBus.$on('preview-canvas', this.previewCanvas);
  },
  beforeDestroy() {
    EventBus.$off('save-canvas', this.saveCanvas);
    EventBus.$off('preview-canvas', this.previewCanvas);
  },
  methods: {
    previewCanvas() {
      this.previewSchema = this.$refs.editorCanvas.canvasComponents;
      this.previewVisible = true;
    },
    saveCanvas() {
      const canvasData = this.$refs.editorCanvas.canvasComponents;
      const json = JSON.stringify(canvasData, null, 2);
      const blob = new Blob([json], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'canvas-schema.json';
      a.click();
      URL.revokeObjectURL(url);
      alert('画布配置已保存为 canvas-schema.json');
    }
  }
};
</script>

<style scoped>
.editor-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.editor-container {
  display: flex;
  flex: 1;
  overflow: hidden; /* Prevent layout from breaking */
}
</style>